package com.shujia;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

/**
 * @author yangjiming
 * @create 2021-04-16 18:41
 */
public class HiveUDTF extends GenericUDTF {

    // 指定输出的列名 及 类型
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        ArrayList<String> filedNames = new ArrayList<String>();
        ArrayList<ObjectInspector> filedObj = new ArrayList<ObjectInspector>();
        filedNames.add("col1");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("col2");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        return ObjectInspectorFactory.getStandardStructObjectInspector(filedNames, filedObj);
    }

    @Override
    public void process(Object[] objects) throws HiveException {
        //"key1:value1,key2:value2,key3:value3"
        String s = objects[0].toString();
        String[] split = s.split(",");
        for (String s1 : split) {
            String[] split1 = s1.split(":");
            String key = split1[0];
            String value = split1[1];
            Object[] obj = new Object[2];
            obj[0]=key;
            obj[1]=value;
            forward(obj);
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
